# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import api, fields, models, _

import datetime

from . import tools

import logging
_logger = logging.getLogger(__name__)

class CrSafetyAlertType(models.Model):

    _name = "cr.safety.alert.type"
    _description = "cr.safety.alert.type"

    name = fields.Char()
    job_type = fields.Selection([
        ('staff', '职工'),
        ('manager', '干部')], default='manager')



class CrSafetyAlert(models.Model):
    _name = "cr.safety.alert"
    _description = "cr.safety.alert"

    name = fields.Char()

    date = fields.Date('date')
    date_year = fields.Char( 'date_year',  compute ='_compute_date_month', store=True)
    date_year_name = fields.Char( 'date_year_name',  compute ='_compute_date_month')
    date_month = fields.Char( 'date_month',  compute ='_compute_date_month', store=True)
    date_month_name = fields.Char( 'date_month_name',  compute ='_compute_date_month')
    num_by_year = fields.Integer()

  
    employee_id = fields.Many2one('hr.employee', 'employee_id'  )
    employee_name = fields.Char( 'employee_name',  related ='employee_id.name')
    employee_barcode = fields.Char( 'employee_barcode',  related ='employee_id.barcode')
    employee_job_type = fields.Selection([
        ('staff', '职工'),
        ('manager', '干部')], related= 'employee_id.job_type')
    employee_job_id = fields.Many2one('hr.job', 'employee_job_id', related='employee_id.job_id' )

    department_id = fields.Many2one(
        'hr.department', 'department_id', 
        related='employee_id.department_id', store=True)

    #employee_dept_id = fields.Many2one('hr.department', 'employee_dept_id', related='employee_id.dept_id' )

    solution = fields.Text()

    state = fields.Selection([
        ('todo', '未审核'),
        ('doing', '未通过'),
        ('done', '已审核')], default='todo')

    type_id = fields.Many2one('cr.safety.alert.type', 'type_id'  )


    @api.depends('date')
    def _compute_date_month(self ):
        for rec in self:
            rec.date_year = datetime.datetime.strftime(rec.date, "%Y") + '-01-01'
            rec.date_year_name = datetime.datetime.strftime(rec.date, "%Y")
            rec.date_month = datetime.datetime.strftime(rec.date, "%Y-%m") + '-01'
            rec.date_month_name = datetime.datetime.strftime(rec.date, "%Y-%m")


    # TBDCODE,  被其他调用, type_id_ref 是 xml
    def find_or_create(self, date_month, employee_id, type_id_ref):
        type_id = self.env['ir.model.data'].xmlid_to_res_id(type_id_ref, True)
        domain = [
            ['date_month', '=', date_month],
            ['employee_id', '=', employee_id],
            ['type_id', '=',type_id],
        ]

        obj = self.search(domain)

        if obj:
            return obj

        vals = {
            'date':  date_month,
            'employee_id': employee_id,
            'type_id': type_id
        }

        obj = self.create(vals)
        obj.name = obj.date_month_name + ' ' + obj.type_id.name
        return obj



    @api.model
    def create( self, values ):
        rec = super( CrSafetyAlert, self).create(values)
        rec._update_lost_credit()
        
        return rec


    def write( self, values ):
        ret = super( CrSafetyAlert, self).write(values)
        for rec in self:
            rec._update_lost_credit()

        return ret


    def _update_lost_credit(self):

        # 月内, 被预警两次
        # 该条之外, 同一人同一月 有预警
        domain = [
            ['date_month', '=', self.date_month ],
            ['employee_id','=', self.employee_id.id],
            ['state','=','done'],
            ['id','!=',self.id]
        ]

        obj = self.search(domain)
        if not obj:
            return None

        type_id_ref = 'cr_safety.safety_lost_credit_type_1002'

        alert_obj = self.env['cr.safety.lost.credit']
        ret = alert_obj.find_or_create(
            self.date_month, self.employee_id.id, type_id_ref)

        return ret


